package cn.corgy.module.compress.deflate;

import cn.corgy.module.compress.Compress;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.DeflaterInputStream;
import java.util.zip.DeflaterOutputStream;

public class DeflaterCompress implements Compress {

    private static final int BUFFER_SIZE = 1024 * 4;

    @Override
    public byte[] compress(byte[] bytes) {
        if (bytes == null) {
            throw new NullPointerException("bytes为空");
        }
        try (ByteArrayOutputStream out = new ByteArrayOutputStream();
             DeflaterOutputStream deflater = new DeflaterOutputStream(out)) {
            deflater.write(bytes);
            deflater.flush();
            deflater.finish();
            return out.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(" deflater 压缩错误", e);
        }
    }

    @Override
    public byte[] decompress(byte[] bytes) {
        if (bytes == null) {
            throw new NullPointerException("bytes为空");
        }
        try (ByteArrayOutputStream out = new ByteArrayOutputStream();
             DeflaterInputStream deflater = new DeflaterInputStream(new ByteArrayInputStream(bytes))) {
            byte[] buffer = new byte[BUFFER_SIZE];
            int n;
            while ((n = deflater.read(buffer)) > -1) {
                out.write(buffer, 0, n);
            }
            return out.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(" deflater 解压错误", e);
        }
    }
}
